package net.kazed.nextaction;

import java.util.HashMap;
import java.util.Map;

import net.kazed.nextaction.database.ContextCache;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.database.TaskType;
import android.app.Application;
import android.database.ContentObserver;
import android.os.Handler;
import android.util.Log;

/**
 * Application class for NextAction.
 * @author Koert Zeilstra
 */
public class NextActionApplication extends Application {

   private ContextCache contextCache;
   private Map<TaskType, Integer> typeResourceMap;

   /**
    * @return Cache for contexts.
    */
   public ContextCache getContextCache() {
      if (contextCache == null) {
         contextCache = new ContextCache(getContentResolver());
         Handler handler = new Handler();
         getContentResolver().registerContentObserver(GtdContext.CONTENT_URI, true, new ContentObserver(handler) {
            @Override
            public boolean deliverSelfNotifications() {
               return true;
            }
            @Override
            public void onChange(boolean selfChange) {
               super.onChange(selfChange);
               contextCache.clearCache();
               Log.d("NextActionApplication", "context content changed");
            }
            
         });
         getContentResolver().registerContentObserver(Task.CONTENT_URI, true, new ContentObserver(handler) {
            @Override
            public boolean deliverSelfNotifications() {
               return true;
            }
            @Override
            public void onChange(boolean selfChange) {
               super.onChange(selfChange);
               contextCache.clearCache();
               Log.d("NextActionApplication", "task content changed");
            }
            
         });
      }
      return contextCache;
   }

   /**
    * @param contextCache Cache for contexts.
    */
   public void setContextCache(ContextCache contextCache) {
      this.contextCache = contextCache;
   }
   
   /**
    * @return Map to translate TaskType to resource ID.
    */
   public Map<TaskType, Integer> getTypeResourceMap() {
       if (typeResourceMap == null) {
           typeResourceMap = new HashMap<TaskType, Integer>();
           typeResourceMap.put(TaskType.IDEA, R.string.task_type_someday);
           typeResourceMap.put(TaskType.NEXT_ACTION, R.string.task_type_next_action);
           typeResourceMap.put(TaskType.UNPROCESSED, R.string.task_type_unprocessed);
           typeResourceMap.put(TaskType.WAITING, R.string.task_type_waiting);
       }
       return typeResourceMap;
   }
   
}
